package com.joizhang.seckill.controller;

import com.joizhang.seckill.api.service.UserService;
import com.joizhang.seckill.api.vo.UserVo;
import com.joizhang.seckill.utils.Result;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import static com.joizhang.seckill.api.service.UserService.COOKIE_NAME_TOKEN;

@Controller
@RequestMapping("/user")
public class UserController {

    @DubboReference
    private UserService userService;

    @RequestMapping("/info")
    @ResponseBody
    public Result<UserVo> getUser(Long id) {
        UserVo userVo = userService.getUserById(id);
        return Result.success(userVo);
    }

    @RequestMapping("/token")
    @ResponseBody
    public Result<UserVo> getToken(HttpServletResponse response, String token) {
        UserVo userVo = userService.getUserByTokenFromCache(token);
        // 延长有效期，有效期等于最后一次操作 + 有效期
        if (userVo != null) {
            Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
            cookie.setMaxAge(3600 * 24 * 2);
            // 设置为网站根目录
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return Result.success(userVo);
    }

}